import React, {Component} from 'react';
import MessageQueue from 'pubsub-js';

class ListExhibit extends Component {

    state = {
        users: [], //用户数据
        isFirst: true,  //是否第一次打开页面
        isLoading: false, //标识是否处于加载中
        err: ''
    }

    // 组件挂载页面后订阅消息
    componentDidMount() {
        this.token = MessageQueue.subscribe('searchUser', (_, data) => {
            this.setState({...data})
        });
    }

    // 卸载组件取消消息订阅
    componentWillUnmount() {
        MessageQueue.unsubscribe(this.token)
    }

    render() {
        const {users, isFirst, isLoading, err} = this.state
        return (
            <div className="row">
                {
                    isFirst ? <h3>Input Search...</h3> :
                        isLoading ? <h3>Loading...</h3> :
                            err !== '' ? <h3 style={{color: 'red'}}>{err}</h3> :
                                users.map(user => {
                                    return (
                                        <div key={user.id} className="card">
                                            <a href={user.html_url} rel="noreferrer" target="_blank">
                                                <img alt="userImg" src={user.avatar_url} style={{width: '100px'}}/>
                                            </a>
                                            <p className="card-text">{user.login}</p>
                                        </div>
                                    )
                                })}
            </div>
        );
    }

}

export default ListExhibit;